#!./env/bin/python3.10
import logging
import time
import validators
import os
from sys import exit

from download import get_info_yt_video, get_mp3_from_yt
from mp3tag import modified_id3
from feed import CheckFeed
from agent import send_audio
from args import ArgParser


arg_parser = ArgParser()
arg_parser.parse()

logging.basicConfig(
        format='%(asctime)s %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S',
        level=logging.INFO)

#TODO make TUI with ncurses


yt_feed = CheckFeed()

def print_video_list():
    videos = yt_feed.read()
    os.system('cls' if os.name == 'nt' else 'clear')
    print("The list of titles of new items in youtube channel:")
    if videos:
        for i, v in enumerate(videos):
            is_live = "[live]" if v.is_live else ""
            print(f"=== {i + 1}.{is_live} {v.title} ({v.id})")

    else:
        print("ERROR: Can't get any videos")

def get_menu_choose_video():

    while True:
        select = input("Insert num of video to convert or type command exit/link/list: ")
        if select == "exit":
            logging.info("Terminate the script")
            exit()
        elif select == "list":
            print_video_list()
        elif select == "link":
            while True:
                link = input("Insert the valid link to youtube video: ")
                if validators.url(link):
                    break
            video = get_info_yt_video(link)
            print(f"Video title is: {video.title}")
            break
        else:
            num_of_items = len(yt_feed.videos)
            try:
                video_index = int(select) - 1
                if 0 <= video_index < num_of_items:
                    video = yt_feed.videos[video_index]
                    return video
                else:
                    logging.warning(f"Number is not from range (1, {num_of_items}). Try again")
            except ValueError:
                logging.warning("ERROR! It's not integer. Try again")


def get_tags_for_video():

    while True:
        answer = input("Type the tags for mp3 file. Format: artist|title: ")
        tags = answer.split("|")
        if len(tags) == 2:
            print(f"----Artist: {tags[0]}\n----Title: {tags[1]}")
            if input("Is it right? y/n: ").lower() != "n":
                return tags
        else:
            logging.warning("This is not right string")


def check_is_stream(video):
    while True:
        if get_info_yt_video(video.link).is_live:
            logging.warning('This stream is on. Waiting for end')
            time.sleep(30 * 60)
        else:
            break

def download_and_send(video, tags):
    logging.info("Start Downloading")
 
    try:
        get_mp3_from_yt(video)
    except Exception:
        raise RuntimeError("Something bad happened")
    else:
        files = [f for f in os.listdir() if f.endswith(".mp3") and f.startswith(video.title[:9])]
        # files = [f for f in os.listdir() if f.endswith(".mp3")]
        if len(files) == 1:
            file_name = files[0]
        else:
            raise RuntimeError("Something bad happened")

        print(f"Video title is: {video.title}")


        modified_id3(file_name, tags[0], tags[1])
        logging.info(f"----DONE!\n----File name: {file_name}")
        send_audio(file_name, tags[0], tags[1])
        logging.info("Uploading completed")
        if os.path.isfile(file_name):
            os.remove(file_name)
            logging.info(f"file {file_name} was removed")
        else:
            logging.warning("File doesn't exists! Remove all mp3 files in folder")
            dir_name = os.getcwd()
            files = os.listdir(dir_name)
            for file in files:
                if file.endswith(".mp3"):
                    os.remove(os.path.join(dir_name, file))

def main():
    link = arg_parser.args.link
    if not link:
        print_video_list()
        video = get_menu_choose_video()
    else:
        video = get_info_yt_video(link)
        print(f"Video title is: {video.title}")
        arg_parser.args.link = None

    tags = get_tags_for_video()

    check_is_stream(video)

    download_and_send(video, tags) 
    main()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print('\n=========== Exit ===============')
